﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace DBCore
{
    public class TypeAttr
    {
        public TypeAttr(Type type)
        {
            ThisType = type;
        }
        public Type ThisType { get; set; }
        private List<string> _parentTypes;
        public List<string> ParentTypes
        {
            get
            {
                if (_parentTypes != null)
                {
                    return _parentTypes;
                }
                else
                {
                    _parentTypes = new List<string>();
                    var t = ThisType.BaseType;
                    while (t != null)
                    {
                        _parentTypes.Add(t.FullName);
                        t = ThisType.BaseType;
                    }
                    var inters = ThisType.GetInterfaces();
                    foreach (var i in inters)
                    {
                        _parentTypes.Add(i.FullName);
                    }
                    return _parentTypes;
                }
            }
            set
            {
                _parentTypes = value;
            }
        }
        public List<string> _childTypes;
        public List<string> ChildTypes
        {
            get
            {
                if (_childTypes != null)
                {
                    return _childTypes;
                }
                else
                {
                    _childTypes = new List<string>();
                    foreach (var kv in IOC.Types)
                    {
                        if (kv.Value.ThisType.IsSubclassOf(ThisType) || kv.Value.ThisType.GetInterfaces().ToList().Exists(type => type == ThisType || type.GUID == ThisType.GUID || type.FullName == ThisType.FullName))
                        {
                            _childTypes.Add(kv.Value.ThisType.FullName);
                        }
                    }
                    return _childTypes;
                }
            }
            set
            {
                _childTypes = value;
            }
        }

        public static implicit operator TypeAttr(Type type)
        {
            return new TypeAttr(type);
        }
    }
}
